local app = require "app"
local gamelib = require "club.threecard.gamelib"
local game = app.game.running

local Time = CS.UnityEngine.Time

local M = gamelib.ui.element()

M.store_watchers = {
    machine = {
        ["更新下注档位"] = function(self, store, state, args, init)
            if init and store.getters.bet_value <= 0 then
                return
            end

            self:update()
        end,

        ["改变下注"] = function(self, store, state, args, init)
            if init then
                return
            end

            self:update()
        end,
    }
}

function M:ctor(res)
    self.res = res or "club.threecard.slotlib/ui/common.b:jackpot"
    self.map = {}
    self.current_bet_value = nil
    self.co = gamelib.coroutine.start(function()
        while true do
            if self.current_bet_value then
                local jp = self.map[self.current_bet_value]
                self.value_txt.text = jp.current
                jp.current = jp.current + jp.speed
                if jp.current >= jp.max then
                    jp.current = jp.base
                end
            end

            gamelib.coroutine.wait(0.1)
        end
    end)
end

function M:update()
    local value = game.store.machine.getters.bet_value

    if not self.map[value] then
        local speed = math.floor(value * Time.deltaTime)
        if speed == 0 then
            speed = 1
        end

        local base = value * 10000 + speed * math.random(1, 100) + math.random(value * 10000 * 0.1, value * 10000 * 0.5)
        local max = base + (speed * 60 * 60)
        self.map[value] = {base = base, speed = speed, max = max, current = base}
    end

    self.current_bet_value = value
end

return M